
/**  
* @Title: MapWrapperFactory.java
* @Package com.wq.mybatis
* @Description: 
* @author likai
* @date 2017年7月30日
* @version V1.0  
*/

package com.utils.mybatis;

import java.util.Map;

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;

/**
 * @ClassName: MapWrapperFactory
 * @Description: mybatis驼峰式实现工厂
 * @author likai
 * @date 2017年7月30日
 *
 */

public class MapWrapperFactory implements ObjectWrapperFactory {

	@Override
	public boolean hasWrapperFor(Object object) {
		return object != null && object instanceof Map;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
		return new MyMapWrapper(metaObject, (Map) object);
	}

	public class MyMapWrapper extends MapWrapper {
		public MyMapWrapper(MetaObject metaObject, Map<String, Object> map) {
			super(metaObject, map);
		}

		@Override
		public String findProperty(String name, boolean useCamelCaseMapping) {
			if (useCamelCaseMapping && ((name.charAt(0) >= 'A' && name.charAt(0) <= 'Z') || name.indexOf("_") >= 0)) {
				return underlineToCamelhump(name);
			}
			return name;
		}

		/**
		 * 将下划线风格替换为驼峰风格
		 *
		 * @param inputString
		 * @return
		 */
		public String underlineToCamelhump(String inputString) {
			StringBuilder sb = new StringBuilder();

			boolean nextUpperCase = false;
			for (int i = 0; i < inputString.length(); i++) {
				char c = inputString.charAt(i);
				if (c == '_') {
					if (sb.length() > 0) {
						nextUpperCase = true;
					}
				} else {
					if (nextUpperCase) {
						sb.append(Character.toUpperCase(c));
						nextUpperCase = false;
					} else {
						sb.append(Character.toLowerCase(c));
					}
				}
			}
			return sb.toString();
		}
	}

}
